package parent.tv.jiaxiaotong.ruanko.com.advancetextswitcher.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;
import android.widget.TextSwitcher;
import android.widget.TextView;

import parent.tv.jiaxiaotong.ruanko.com.advancetextswitcher.R;

/**
 * 相关知识参考：http://blog.csdn.net/mapdigit/article/details/8130908
 */
public class AdvTextSwitcher extends TextSwitcher {
    private Context mContext;
    private String[] mTexts = {};
    private int currentPos;
    private AdvTextSwitcher.Callback mCallback = new Callback() {
        @Override
        public void onItemClick(int position) {
        }
    };

    public AdvTextSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        int[] attrsArray = new int[]{
                android.R.attr.textColor,
                R.attr.textSize,
                android.R.attr.inAnimation,
                android.R.attr.outAnimation,
                R.attr.gravity
        };
        TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
        final int textColor = ta.getColor(0, Color.BLACK);
        final float textSize = ta.getDimensionPixelSize(1, 20);
        final int animInRes = ta.getResourceId(2, R.anim.fade_in_slide_in);
        final int animOutRes = ta.getResourceId(3, R.anim.fade_out_slide_out);
        boolean right = (ta.getInt(4, 0) & 0x01) == 0x01;
        boolean left = (ta.getInt(4, 0) & 0x02) == 0x02;
        boolean center = (ta.getInt(4, 0) & 0x03) == 0x03;
        final int gravity = center ? Gravity.CENTER :
                (right ? Gravity.RIGHT | Gravity.CENTER_VERTICAL :
                        (left ? (Gravity.LEFT | Gravity.CENTER_VERTICAL)
                                : Gravity.NO_GRAVITY)
                );
        ta.recycle();
        this.setFactory(new ViewFactory() {
            public View makeView() {
                TextView innerText = new TextView(mContext);
                innerText.setGravity(gravity);
                innerText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
                innerText.setTextColor(textColor);
                innerText.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View p1) {
                        AdvTextSwitcher.this.onClick();
                    }
                });
                return innerText;
            }
        });

        Animation animIn = AnimationUtils.loadAnimation(mContext, animInRes);
        Animation animOut = AnimationUtils.loadAnimation(mContext, animOutRes);

        //--------------------------------下面两个是3D翻转动画--------------------------------------------------
        //从上往下翻
        //animIn = createRotate3dAnimation(90, 0, true, false);
        //animOut = createRotate3dAnimation(0, -90, false, false);

        //从下往上翻
        //animIn = createRotate3dAnimation(-90, 0, true, true);
        //animOut = createRotate3dAnimation(0, 90, false, true);
        //----------------------------------------------------------------------------------

        this.setInAnimation(animIn);
        this.setOutAnimation(animOut);
    }

    public void overrideText(String text) {
        this.setText(text);
    }

    public void setAnim(int animInRes, int animOutRes) {
        Animation animIn = AnimationUtils.loadAnimation(mContext, animInRes);
        Animation animOut = AnimationUtils.loadAnimation(mContext, animOutRes);
        this.setInAnimation(animIn);
        this.setOutAnimation(animOut);
    }

    public void setAnim(Animation animIn, Animation animOut) {
        this.setInAnimation(animIn);
        this.setOutAnimation(animOut);
    }

    public void setTexts(String[] texts) {
        if (texts.length > 0) {
            this.mTexts = texts;
            this.currentPos = 0;
        }
        updateDisp();
    }

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }

    public void next() {
        if (mTexts.length > 0) {
            if (currentPos < mTexts.length - 1) {
                currentPos++;
            } else {
                currentPos = 0;
            }
            updateDisp();
        }
    }

    public void previous() {
        if (mTexts.length > 0) {
            if (currentPos > 0) {
                currentPos--;
            } else {
                currentPos = mTexts.length - 1;
            }
            updateDisp();
        }
    }

    public interface Callback {
        public void onItemClick(int position);
    }

    private void updateDisp() {
        this.setText(mTexts[currentPos]);
    }

    private void onClick() {
        mCallback.onItemClick(currentPos);
    }

    private Rotate3dAnimation createRotate3dAnimation(float start, float end, boolean turnIn, boolean turnUp) {
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
        rotation.setDuration(800);
        rotation.setFillAfter(false);
        rotation.setInterpolator(new AccelerateInterpolator());
        return rotation;
    }

    /**
     * 项目名称：AdvanceTextSwitcher
     * 类名称：
     * 类描述：
     * 创建人：Aman
     * 创建时间：2016-7-20  15:10:07
     * 修改人：Aman
     * 修改时间：2016-7-20  15:10:07
     * 修改备注：
     *
     * @version V1.0
     */
    public class Rotate3dAnimation extends Animation {
        private final float mFromDegrees;
        private final float mToDegrees;
        private float mCenterX;
        private float mCenterY;
        private final boolean mTurnIn;
        private final boolean mTurnUp;
        private Camera mCamera;

        public Rotate3dAnimation(float fromDegrees, float toDegrees, boolean turnIn, boolean turnUp) {
            mFromDegrees = fromDegrees;
            mToDegrees = toDegrees;
            mTurnIn = turnIn;
            mTurnUp = turnUp;
        }

        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            mCamera = new Camera();
            //初始化中间坐标
//            mCenterY = getHeight() / 2;
//            mCenterX = getWidth() / 2;
            mCenterX = width / 2;
            mCenterY = height / 2;
        }

        /**
         * Transformation中则包含一个矩阵和alpha值,矩阵是用来做平移，旋转和缩放动画的，而alpha值是用来做alpha动画的
         *
         * @param interpolatedTime interpolatedTime
         * @param t                t
         */
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            final float fromDegrees = mFromDegrees;
            float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

            final float centerX = mCenterX;
            final float centerY = mCenterY;
            //Camera:一个空间变换工具，类似于Matrix，提供了各种变换方法，如 translate和rotateY等。
            final Camera camera = mCamera;
            final int derection = mTurnUp ? 1 : -1;
            //Matrix:一个三维的矩阵变换函数。
            final Matrix matrix = t.getMatrix();

            camera.save();
            if (mTurnIn) {
                camera.translate(0.0f, derection * mCenterY * (interpolatedTime - 1.0f), 0.0f);
            } else {
                camera.translate(0.0f, derection * mCenterY * (interpolatedTime), 0.0f);
            }
            camera.rotateX(degrees);
            camera.getMatrix(matrix);//计算当前的矩阵变换，并将其复制到矩阵matrix中。
            camera.restore();

            matrix.preTranslate(-centerX, -centerY);//执行矩阵指定的转换
            matrix.postTranslate(centerX, centerY);//执行矩阵指定的转换
        }
    }
}